<template>
  <Container>
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="search"></SearchForm>
    </template>
    <template v-slot:btnList>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:content v-loading="loading">
      <div class="tableModule">
        <TableData :tableThead="tableThead" :config="table_config" :dataList="dataList" :loading="loading" :page="page"
          :size="size" :total="total" @selection-change="selectionChange" @handleCurrentChange="handleCurrentChange"
          @handleSizeChange="handleSizeChange">
          <template v-slot:equipmentValue="{ row }">
            {{ row.equipmentValue }}{{ row.energyUnit }}
          </template>
          <template v-slot:consumption="{ row }">
            {{ row.consumption||0 }}{{ row.energyUnit }}
          </template>
        </TableData>
      </div>
    </template>
    <template v-slot:footer></template>
    <template v-slot:dialogModule>
      <AddEdit :title="'抄表'" @closeDialog="closeDialog" :areaList="areaList" :energyList="energyList"
        :personList="personList" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
  </Container>
</template>

<script>
import Container from "@/components/Container"
import AddEdit from './components/addEdit.vue';
import manualMeterApi from '@/api/manualMeter'
import areaApi from "@/api/area"
import energyApi from "@/api/energy"
import organizationApi from '@/api/organization.js'
export default {
  name: 'ManualMeterReadingEntry',
  components: { AddEdit, Container },
  data() {
    return {
      dialogVisible: false,
      addEditFlag: 'add',
      btnList: ['add', 'delete'],
      size: 10,
      page: 1,
      total: 10,
      dataList: [],
      formItemList: [
        {
          label: '选择区域',
          type: 'select',
          selectOptions: [],
          param: 'areaId',
          defaultSelect: '',
          multiple: false,
        },
        {
          label: '抄表类型',
          type: 'select',
          selectOptions: [],
          param: 'energyId',
          defaultSelect: '',
          multiple: false,
        },
        {
          label: '抄表人',
          type: 'select',
          selectOptions: [],
          param: 'recordUser',
          defaultSelect: '',
          multiple: false,
        },
        {
          label: '抄表时间',
          type: 'datetimerange',
          param: 'dateTime',
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd'
        },
      ],
      tableThead: [
        { label: '区域名称', prop: 'areaName' },
        { label: '抄表类型', prop: 'energyName' },
        { label: '累计用量', slotName: 'equipmentValue' },
        { label: '距上条用量', slotName: 'consumption' },
        { label: '抄表人', prop: 'recordUser' },
        { label: '统计时间', prop: 'recordTime' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '编辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      selectList: [],
      searchFormData: {},
      formData: {}
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    async initData() {
      let { data: areaList } = await areaApi.queryByCondition({});
      let { data: energyList } = await energyApi.queryByCondition({});
      let { data: personList } = await organizationApi.queryByPerson({});
      this.areaList = areaList || [];
      this.energyList = energyList || [];
      this.personList = (personList || []).filter(e => e.person).map(e => {
        return {
          name: e.person.name,
          ...e
        }
      })
      console.log(this.personList)
      this.setFormOptions();
      this.queryPageByCondition();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('areaId') !== -1) {
          let selectOptions = this.areaList.map(data => {
            return {
              text: data.areaName, value: data.areaId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('energyId') !== -1) {
          let selectOptions = this.energyList.map(data => {
            return {
              text: data.energyName, value: data.energyId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('recordUser') !== -1) {
          let selectOptions = this.personList.map(data => {
            return {
              text: data.name, value: data.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    delList(deleteList = [], key = 'manualMeterId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await manualMeterApi.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == 'edit') {
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      } else if (item.flag == 'delete') {
        this.delList([rowData]);
      }
      this.addEditFlag = item.flag
    },
    //查询表单数据
    queryPageByCondition() {
      this.loading = true;
      manualMeterApi.queryPageByCondition({
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
          organizationNo:sessionStorage.organizationNo
        }
      }).then(res => {
        if (res.code == 1) {
          let { content, totalElements, totalPages } = res.data || {}
          this.dataList = content || [];
          this.total = totalElements || 10;
        } else {
          this.dataList = [];
        }
        this.dataList = [{data:0}];
        this.loading = false;
      }).catch(err => {
        this.loading = false;
      })
    },
    search(data) {
      this.page = 1;
      this.searchFormData = {
        ...this.searchFormData,
        ...data,
        startTime: data.dateTime ? data.dateTime[0]+ ' 00:00:00' : '',
        endTime: data.dateTime ? data.dateTime[1] + ' 23:59:59': ''
      };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
}
</script>

<style lang="scss" scoped></style>
